package cn.dgut.lemon.springbootexp03.service;

import cn.dgut.lemon.springbootexp03.model.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lemon
 * @data 2020-11-18 21:36
 */

@EnableScheduling
@Service
//InitializingBean接口为bean提供了初始化方法的方式
public class CoronaVirusDataService implements InitializingBean {

    private static final String DATA_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    private final List<RegionStats> allRegionStats = new ArrayList<>();

    public List<RegionStats> getAllRegionStats() {
        return allRegionStats;
    }

    // 定时，每小时执行一次
    @Scheduled(cron = "0 0 1 * * *")
    public void fetchCoronaVirusData() throws IOException {

        // 爬取csv文件
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Lemon"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();

        // 解析csv文件
        Reader reader = new InputStreamReader(body.getInputStream());
        Iterable<CSVRecord> records = CSVFormat.DEFAULT.RFC4180.withFirstRecordAsHeader().parse(reader);

        // 数据存储
        for (CSVRecord record : records) {
            RegionStats regionStats = new RegionStats();
            regionStats.setState(record.get("Province/State"));
            regionStats.setCountry(record.get("Country/Region"));
            regionStats.setLatestTotalCases(Integer.parseInt(record.get(record.size() - 1)));
            regionStats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size() - 1))
                    - Integer.parseInt(record.get(record.size() - 2)));
            allRegionStats.add(regionStats);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        fetchCoronaVirusData();
    }
}
